package com.netdisk.controller;

import com.netdisk.dto.UserActivityDTO;
import com.netdisk.entity.UserActivity;
import com.netdisk.service.UserActivityService;
import com.netdisk.service.UserService;
import com.netdisk.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户活动日志控制器
 */
@Api(tags = "用户活动日志")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserActivityController {

    @Autowired
    private UserActivityService userActivityService;

    @Autowired
    private UserService userService;

    @ApiOperation("获取用户最近活动")
    @GetMapping("/activities")
    public Result<List<UserActivityDTO>> getRecentActivities(
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            @ApiParam(value = "最大记录数", defaultValue = "10") @RequestParam(value = "limit", defaultValue = "10") Integer limit,
            HttpServletRequest request) {
        
        log.info("获取用户ID={}的最近{}条活动日志", userId, limit);
        
        // 检查用户是否存在
        if (userService.getById(userId) == null) {
            return Result.error(404, "用户不存在");
        }
        
        // 限制limit的范围，防止请求过多数据
        if (limit <= 0) {
            limit = 10;
        } else if (limit > 50) {
            limit = 50;
        }
        
        // 获取最近活动日志
        List<UserActivity> activities = userActivityService.getRecentActivities(userId, limit);
        
        // 转换为DTO
        List<UserActivityDTO> dtoList = activities.stream().map(activity -> {
            UserActivityDTO dto = new UserActivityDTO();
            BeanUtils.copyProperties(activity, dto);
            return dto;
        }).collect(Collectors.toList());
        
        return Result.success(dtoList);
    }
} 